// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// S [author] rhyme_lph
// s [email]  rhymelph@gmail.com
// s [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/invoice_entity.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/widgets/select/invoice_number_check_box.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/invoice/record_payment_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_white_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "recordPaymentPage")
class RecordPaymentPage extends StatefulWidget {
  @override
  _RecordPaymentPageState createState() => _RecordPaymentPageState();
}

class _RecordPaymentPageState extends State<RecordPaymentPage>
    with PagePresenter<RecordPaymentPage, RecordPaymentProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.receive_payment,
      );

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: super.buildEmptyWidget,
                ),
              ],
            ),
            _buildBottomBar()
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                Expanded(
                  child: listBuilder<Map<String, List<InvoiceEntity>>>(
                    selector: (_, __) => Map.from(__.groupMap),
                    builder: (BuildContext context,
                        Map<String, List<InvoiceEntity>> value, Widget child) {
                      return value.isEmpty
                          ? super.buildEmptyWidget
                          : CustomScrollView(
                              slivers: buildSearchWidget(),
                            );
                    },
                  ),
                ),
              ],
            ),
            _buildBottomBar()
          ],
        ),
      );

  Widget _buildBottomBar() => Positioned(
      bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
      left: 0.0,
      right: 0.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatTextWhiteButton(
            title: S.current.cancel,
            onTap: provider.onCancel,
          ),
          SizedBox(
            width: getDp(15),
          ),
          NormalFloatTextButton(
            title: S.current.record,
            onTap: provider.onAdd,
          ),
        ],
      ));

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<InvoiceEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sticky: false,
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data[i]),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return TransactionRecordTitleItem(
      title: _title,
    );
  }

  Widget buildSliverItem(InvoiceEntity data) {
    InvoiceEntity lastItemInList =
        provider.groupMap.entries.toList().map((e) => e.value).last.last;

    return listBuilder<Tuple2<InvoiceEntity, bool>>(
      selector: (_, __) => Tuple2(
          data,
          __.invoiceList.firstWhere((element) => element.id == data.id,
                  orElse: () => null) !=
              null),
      builder: (BuildContext context, Tuple2<InvoiceEntity, bool> value,
              Widget child) =>
          Column(
        children: [
          PressedOpacityButton(
            onPressed: () => provider.onSelect(value.item1),
            child: InvoiceNumberCheckBox(
              title: value.item1?.contact?.name ?? '',
              billNumber: value.item1.number,
              due: DateTimeUtils.formatDateTimeString(value.item1.dueAt),
              amount: value.item1.total.toDouble(),
              unit: value.item1.currencyCode,
              status: value.item1.isOverdue == 1 && value.item1.status == 'open'
                  ? 'Overdue'
                  : FormUtils.getStatus(ReimburseModel.invoice,
                      value.item1.status, value.item1.unpaid),
              isSelect: value.item2,
            ),
          ),
          if (lastItemInList == value.item1) AppSpaces.h85(context),
        ],
      ),
    );
  }
}
